package com.cskaoyan.config;

import com.cskaoyan.realm.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author
 * @date 2020/12/8 21:22
 */
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        //所有的realm
        Collection<Realm> originalRealms = this.getRealms();
        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();
        //根据type进行分发
        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm originalRealm : originalRealms) {
            if (originalRealm.getName().toLowerCase().contains(type)) {
                realms.add(originalRealm);
            }
        }
        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) :
                this.doMultiRealmAuthentication(realms, authenticationToken);
    }
}
